{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "fancy-chain",
   "metadata": {},
   "outputs": [],
   "source": [
    "from code.ftquoteapi import quoteapi\n",
    "#import imp"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "id": "alone-oasis",
   "metadata": {},
   "outputs": [],
   "source": [
    "#imp.load_module(quote)\n",
    "#imp.reload(futuquote)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "educational-cornwall",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2021-03-01 10:02:23,638 [open_context_base.py] _socket_reconnect_and_wait_ready:255: Start connecting: host=127.0.0.1; port=11111;\n",
      "2021-03-01 10:02:23,641 [open_context_base.py] on_connected:344: Connected : conn_id=1; \n",
      "2021-03-01 10:02:23,764 [open_context_base.py] _handle_init_connect:445: InitConnect ok: conn_id=1; info={'server_version': 500, 'login_user_id': 716900, 'conn_id': 6771972846163192990, 'conn_key': '8CA73900D8924CD2', 'conn_iv': 'A6FED6D94F5116E5', 'keep_alive_interval': 10, 'is_encrypt': False};\n"
     ]
    }
   ],
   "source": [
    "hq = quoteapi()\n",
    "query = hq.init_context()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "combined-cream",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "None\n"
     ]
    }
   ],
   "source": [
    "print(query)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "robust-tradition",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(0, {'market_sz': 'MORNING', 'market_us': 'AFTER_HOURS_END', 'market_sh': 'MORNING', 'market_hk': 'MORNING', 'market_hkfuture': 'FUTURE_DAY_OPEN', 'market_usfuture': 'FUTURE_OPEN', 'server_ver': '500', 'trd_logined': True, 'timestamp': '1614564151', 'qot_logined': True, 'local_timestamp': 1614564151.745279, 'program_status_type': 'READY', 'program_status_desc': ''})\n"
     ]
    }
   ],
   "source": [
    "gs = hq.get_global_state()\n",
    "print(gs)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "pediatric-internship",
   "metadata": {},
   "outputs": [
    {
     "ename": "NameError",
     "evalue": "name 'OrderBookHandlerBase' is not defined",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mNameError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-6-ddb4db16e5b2>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[1;32m      1\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mfutu\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0;32mclass\u001b[0m \u001b[0mOrderBookTest\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mOrderBookHandlerBase\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m      3\u001b[0m     \u001b[0;32mdef\u001b[0m \u001b[0mon_recv_rsp\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mrsp_pb\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m      4\u001b[0m         \u001b[0mret_code\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mdata\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0msuper\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mOrderBookTest\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mon_recv_rsp\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mrsp_pb\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m      5\u001b[0m         \u001b[0;32mif\u001b[0m \u001b[0mret_code\u001b[0m \u001b[0;34m!=\u001b[0m \u001b[0mRET_OK\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;31mNameError\u001b[0m: name 'OrderBookHandlerBase' is not defined"
     ]
    }
   ],
   "source": [
    "import futu\n",
    "class OrderBookTest(OrderBookHandlerBase):\n",
    "    def on_recv_rsp(self, rsp_pb):\n",
    "        ret_code, data = super(OrderBookTest,self).on_recv_rsp(rsp_pb)\n",
    "        if ret_code != RET_OK:\n",
    "            print(\"OrderBookTest: error, msg: %s\" % data)\n",
    "            return RET_ERROR, data\n",
    "        print(\"OrderBookTest \", data) # OrderBookTest自己的处理逻辑\n",
    "        return RET_OK, data\n",
    "    \n",
    "handler = OrderBookTest()\n",
    "hq.context.set_handler(handler)  # 设置实时摆盘回调\n",
    "hq.context.subscribe(['HK.00700'], [SubType.ORDER_BOOK])  # 订阅买卖摆盘类型，FutuOpenD开始持续收到服务器的推送\n",
    "time.sleep(15)  #  设置脚本接收FutuOpenD的推送持续时间为15秒\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "invalid-palace",
   "metadata": {},
   "outputs": [
    {
     "ename": "TypeError",
     "evalue": "'module' object is not callable",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mTypeError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-13-a97e58c6ac6e>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mquote\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0minit_context\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[0;31mTypeError\u001b[0m: 'module' object is not callable"
     ]
    }
   ],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "specific-vitamin",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "dimensional-environment",
   "metadata": {},
   "outputs": [
    {
     "ename": "AttributeError",
     "evalue": "'OpenQuoteContext' object has no attribute 'closecontext'",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mAttributeError\u001b[0m                            Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-8-70e2f137438e>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mhq\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mcontext\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mclosecontext\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[0;31mAttributeError\u001b[0m: 'OpenQuoteContext' object has no attribute 'closecontext'"
     ]
    }
   ],
   "source": [
    "hq.context.closecontext()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "rising-jackson",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2021-02-27 23:14:57,246 [open_context_base.py] _socket_reconnect_and_wait_ready:255: Start connecting: host=127.0.0.1; port=11111;\n",
      "2021-02-27 23:14:57,249 [open_context_base.py] on_connected:344: Connected : conn_id=4; \n",
      "2021-02-27 23:14:57,254 [open_context_base.py] _handle_init_connect:445: InitConnect ok: conn_id=4; info={'server_version': 500, 'login_user_id': 716900, 'conn_id': 6771447524501701379, 'conn_key': '5CBFB215D5926499', 'conn_iv': '0E8AFDFEEAFF1597', 'keep_alive_interval': 10, 'is_encrypt': False};\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'total_used': 1, 'remain': 299, 'own_used': 1, 'sub_list': {'QUOTE': ['HK.00700']}}\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2021-02-27 23:14:57,523 [network_manager.py] work:366: Close: conn_id=4\n"
     ]
    }
   ],
   "source": [
    "from futu import *\n",
    "quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)\n",
    "\n",
    "quote_ctx.subscribe(['HK.00700'], [SubType.QUOTE])\n",
    "ret, data = quote_ctx.query_subscription()\n",
    "if ret == RET_OK:\n",
    "    print(data)\n",
    "else:\n",
    "    print('error:', data)\n",
    "quote_ctx.close() # 结束后记得关闭当条连接，防止连接条数用尽"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "ready-spice",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2021-02-27 23:15:22,334 [open_context_base.py] _socket_reconnect_and_wait_ready:255: Start connecting: host=127.0.0.1; port=11111;\n",
      "2021-02-27 23:15:22,337 [open_context_base.py] on_connected:344: Connected : conn_id=5; \n",
      "2021-02-27 23:15:22,341 [open_context_base.py] _handle_init_connect:445: InitConnect ok: conn_id=5; info={'server_version': 500, 'login_user_id': 716900, 'conn_id': 6771447629726967943, 'conn_key': '4607D915D59240E3', 'conn_iv': '92F213D0EEFF35E0', 'keep_alive_interval': 10, 'is_encrypt': False};\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "OrderBookTest  {'code': 'HK.00700', 'svr_recv_time_bid': '', 'svr_recv_time_ask': '', 'Bid': [(662.5, 238200, 26, {}), (662.0, 212700, 189, {}), (661.5, 214400, 55, {}), (661.0, 360000, 185, {}), (660.5, 223700, 110, {}), (660.0, 1158400, 1301, {}), (659.5, 270100, 26, {}), (659.0, 331500, 87, {}), (658.5, 232300, 31, {}), (658.0, 304700, 242, {})], 'Ask': [(663.5, 200, 1, {}), (664.0, 8600, 2, {}), (664.5, 20000, 1, {}), (665.0, 600, 3, {}), (665.5, 0, 0, {}), (666.0, 0, 0, {}), (666.5, 2500, 2, {}), (667.0, 30100, 2, {}), (667.5, 17800, 4, {}), (668.0, 87200, 13, {})]}\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2021-02-27 23:15:37,365 [network_manager.py] work:366: Close: conn_id=5\n"
     ]
    }
   ],
   "source": [
    "import time\n",
    "from futu import *\n",
    "class OrderBookTest(OrderBookHandlerBase):\n",
    "    def on_recv_rsp(self, rsp_pb):\n",
    "        ret_code, data = super(OrderBookTest,self).on_recv_rsp(rsp_pb)\n",
    "        if ret_code != RET_OK:\n",
    "            print(\"OrderBookTest: error, msg: %s\" % data)\n",
    "            return RET_ERROR, data\n",
    "        print(\"OrderBookTest \", data) # OrderBookTest自己的处理逻辑\n",
    "        return RET_OK, data\n",
    "quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)\n",
    "handler = OrderBookTest()\n",
    "quote_ctx.set_handler(handler)  # 设置实时摆盘回调\n",
    "quote_ctx.subscribe(['HK.00700'], [SubType.ORDER_BOOK])  # 订阅买卖摆盘类型，FutuOpenD开始持续收到服务器的推送\n",
    "time.sleep(15)  #  设置脚本接收FutuOpenD的推送持续时间为15秒\n",
    "quote_ctx.close()  # 关闭当条连接，FutuOpenD会在1分钟后自动取消相应股票相应类型的订阅"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "physical-kitty",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2021-02-27 23:16:08,456 [open_context_base.py] _socket_reconnect_and_wait_ready:255: Start connecting: host=127.0.0.1; port=11111;\n",
      "2021-02-27 23:16:08,459 [open_context_base.py] on_connected:344: Connected : conn_id=6; \n",
      "2021-02-27 23:16:08,464 [open_context_base.py] _handle_init_connect:445: InitConnect ok: conn_id=6; info={'server_version': 500, 'login_user_id': 716900, 'conn_id': 6771447823183816191, 'conn_key': 'DD671F16D5926829', 'conn_iv': 'FA6CD94CFBFF9559', 'keep_alive_interval': 10, 'is_encrypt': False};\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "current subscription status : (0, {'total_used': 1, 'remain': 299, 'own_used': 0, 'sub_list': {'ORDER_BOOK': ['HK.00700']}})\n",
      "subscribe successfully！current subscription status : (0, {'total_used': 3, 'remain': 297, 'own_used': 2, 'sub_list': {'ORDER_BOOK': ['HK.00700'], 'QUOTE': ['HK.00700'], 'TICKER': ['HK.00700']}})\n",
      "unsubscribe all successfully！current subscription status: (0, {'total_used': 1, 'remain': 299, 'own_used': 1, 'sub_list': {'TICKER': ['HK.00700']}})\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2021-02-27 23:17:08,583 [network_manager.py] work:366: Close: conn_id=6\n"
     ]
    }
   ],
   "source": [
    "from futu import *\n",
    "import time\n",
    "quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)\n",
    "\n",
    "print('current subscription status :', quote_ctx.query_subscription())  # 查询初始订阅状态\n",
    "ret_sub, err_message = quote_ctx.subscribe(['HK.00700'], [SubType.QUOTE, SubType.TICKER], subscribe_push=False)\n",
    "# 先订阅了QUOTE和TICKER两个类型。订阅成功后FutuOpenD将持续收到服务器的推送，False代表暂时不需要推送给脚本\n",
    "if ret_sub == RET_OK:   # 订阅成功\n",
    "    print('subscribe successfully！current subscription status :', quote_ctx.query_subscription())  # 订阅成功后查询订阅状态\n",
    "    time.sleep(60)  # 订阅之后至少1分钟才能取消订阅\n",
    "    ret_unsub, err_message_unsub = quote_ctx.unsubscribe(['HK.00700'], [SubType.QUOTE])\n",
    "    if ret_unsub == RET_OK:\n",
    "        print('unsubscribe all successfully！current subscription status:', quote_ctx.query_subscription())  # 取消订阅后查询订阅状态\n",
    "    else:\n",
    "        print('Failed to cancel all subscriptions！', err_message_unsub)\n",
    "else:\n",
    "    print('subscription failed', err_message)\n",
    "quote_ctx.close() # 结束后记得关闭当条连接，防止连接条数用尽"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "increased-manhattan",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2021-02-27 23:17:08,598 [open_context_base.py] _socket_reconnect_and_wait_ready:255: Start connecting: host=127.0.0.1; port=11111;\n",
      "2021-02-27 23:17:08,600 [open_context_base.py] on_connected:344: Connected : conn_id=7; \n",
      "2021-02-27 23:17:08,604 [open_context_base.py] _handle_init_connect:445: InitConnect ok: conn_id=7; info={'server_version': 500, 'login_user_id': 716900, 'conn_id': 6771448075426070292, 'conn_key': '642C7B16D592CCA2', 'conn_iv': 'D5895A17040066C0', 'keep_alive_interval': 10, 'is_encrypt': False};\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Empty DataFrame\n",
      "Columns: [code, data_date, data_time, last_price, open_price, high_price, low_price, prev_close_price, volume, turnover, turnover_rate, amplitude, suspension, listing_date, price_spread, dark_status, sec_status, strike_price, contract_size, open_interest, implied_volatility, premium, delta, gamma, vega, theta, rho, net_open_interest, expiry_date_distance, contract_nominal_value, owner_lot_multiplier, option_area_type, contract_multiplier, last_settle_price, position, position_change, index_option_type, pre_price, pre_high_price, pre_low_price, pre_volume, pre_turnover, pre_change_val, pre_change_rate, pre_amplitude, after_price, after_high_price, after_low_price, after_volume, after_turnover, after_change_val, after_change_rate, after_amplitude]\n",
      "Index: []\n",
      "\n",
      "[0 rows x 53 columns]\n"
     ]
    },
    {
     "ename": "IndexError",
     "evalue": "index 0 is out of bounds for axis 0 with size 0",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mIndexError\u001b[0m                                Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-23-04a484554596>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[1;32m      8\u001b[0m     \u001b[0;32mif\u001b[0m \u001b[0mret\u001b[0m \u001b[0;34m==\u001b[0m \u001b[0mRET_OK\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m      9\u001b[0m         \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mdata\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 10\u001b[0;31m         \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mdata\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m'code'\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m)\u001b[0m   \u001b[0;31m# 取第一条的股票代码\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m     11\u001b[0m         \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mdata\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m'code'\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mvalues\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mtolist\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m   \u001b[0;31m# 转为list\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m     12\u001b[0m     \u001b[0;32melse\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;32m~/.pyenv/versions/3.7.0/lib/python3.7/site-packages/pandas/core/series.py\u001b[0m in \u001b[0;36m__getitem__\u001b[0;34m(self, key)\u001b[0m\n\u001b[1;32m    877\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    878\u001b[0m         \u001b[0;32mif\u001b[0m \u001b[0mis_integer\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mkey\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;32mand\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mindex\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_should_fallback_to_positional\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 879\u001b[0;31m             \u001b[0;32mreturn\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_values\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0mkey\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m    880\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    881\u001b[0m         \u001b[0;32melif\u001b[0m \u001b[0mkey_is_scalar\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;31mIndexError\u001b[0m: index 0 is out of bounds for axis 0 with size 0"
     ]
    }
   ],
   "source": [
    "from futu import *\n",
    "quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)\n",
    "\n",
    "ret_sub, err_message = quote_ctx.subscribe(['HK.00700'], [SubType.QUOTE], subscribe_push=False)\n",
    "# 先订阅K 线类型。订阅成功后FutuOpenD将持续收到服务器的推送，False代表暂时不需要推送给脚本\n",
    "if ret_sub == RET_OK:  # 订阅成功\n",
    "    ret, data = quote_ctx.get_stock_quote(['HK.00700'])  # 获取订阅股票报价的实时数据\n",
    "    if ret == RET_OK:\n",
    "        print(data)\n",
    "        print(data['code'][0])   # 取第一条的股票代码\n",
    "        print(data['code'].values.tolist())   # 转为list\n",
    "    else:\n",
    "        print('error:', data)\n",
    "else:\n",
    "    print('subscription failed', err_message)\n",
    "quote_ctx.close()  # 关闭当条连接，FutuOpenD会在1分钟后自动取消相应股票相应类型的订阅"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "improving-needle",
   "metadata": {},
   "outputs": [],
   "source": [
    "import time\n",
    "from futu import *\n",
    "\n",
    "class StockQuoteTest(StockQuoteHandlerBase):\n",
    "    def on_recv_rsp(self, rsp_pb):\n",
    "        ret_code, data = super(StockQuoteTest,self).on_recv_rsp(rsp_pb)\n",
    "        if ret_code != RET_OK:\n",
    "            print(\"StockQuoteTest: error, msg: %s\" % data)\n",
    "            return RET_ERROR, data\n",
    "        print(\"StockQuoteTest \", data) # StockQuoteTest自己的处理逻辑\n",
    "        return RET_OK, data\n",
    "quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)\n",
    "handler = StockQuoteTest()\n",
    "quote_ctx.set_handler(handler)  # 设置实时报价回调\n",
    "quote_ctx.subscribe(['HK.00700'], [SubType.QUOTE])  # 订阅实时报价类型，FutuOpenD开始持续收到服务器的推送\n",
    "time.sleep(15)  #  设置脚本接收FutuOpenD的推送持续时间为15秒\n",
    "quote_ctx.close()   # 关闭当条连接，FutuOpenD会在1分钟后自动取消相应股票相应类型的订阅    \t"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "handed-arrest",
   "metadata": {},
   "outputs": [],
   "source": [
    "quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)\n",
    "ret_sub = quote_ctx.subscribe(['HK.00700'], [SubType.ORDER_BOOK], subscribe_push=False)[0]\n",
    "# 先订阅买卖摆盘类型。订阅成功后 OpenD 将持续收到服务器的推送，False 代表暂时不需要推送给脚本\n",
    "if ret_sub == RET_OK:  # 订阅成功\n",
    "    ret, data = quote_ctx.get_order_book('HK.00700', num=3)  # 获取一次 3 档实时摆盘数据\n",
    "    if ret == RET_OK:\n",
    "        print(data)\n",
    "    else:\n",
    "        print('error:', data)\n",
    "else:\n",
    "    print('subscription failed')\n",
    "quote_ctx.close()  # 关闭当条连接，OpenD 会在 1 分钟后自动取消相应股票相应类型的订阅"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "id": "prepared-singing",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2021-02-27 23:17:53,631 [open_context_base.py] _socket_reconnect_and_wait_ready:255: Start connecting: host=127.0.0.1; port=11111;\n",
      "2021-02-27 23:17:53,635 [open_context_base.py] on_connected:344: Connected : conn_id=8; \n",
      "2021-02-27 23:17:53,639 [open_context_base.py] _handle_init_connect:445: InitConnect ok: conn_id=8; info={'server_version': 500, 'login_user_id': 716900, 'conn_id': 6771448264322700378, 'conn_key': '4AE4BF16D59280C9', 'conn_iv': 'E277DC160B00B68F', 'keep_alive_interval': 10, 'is_encrypt': False};\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "       code             time_key   open  close   high    low    volume  \\\n",
      "0  HK.00700  2021-02-25 00:00:00  700.0  691.5  717.0  691.5  24008360   \n",
      "1  HK.00700  2021-02-26 00:00:00  669.0  662.5  686.5  662.5  37077103   \n",
      "\n",
      "       turnover  pe_ratio  turnover_rate  last_close  \n",
      "0  1.682761e+10    64.409        0.00250       687.0  \n",
      "1  2.491707e+10    61.708        0.00386       691.5  \n",
      "0.0025\n",
      "[0.0025, 0.00386]\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2021-02-27 23:17:53,706 [network_manager.py] work:366: Close: conn_id=8\n"
     ]
    }
   ],
   "source": [
    "quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)\n",
    "\n",
    "ret_sub, err_message = quote_ctx.subscribe(['HK.00700'], [SubType.K_DAY], subscribe_push=False)\n",
    "# 先订阅K 线类型。订阅成功后FutuOpenD将持续收到服务器的推送，False代表暂时不需要推送给脚本\n",
    "if ret_sub == RET_OK:  # 订阅成功\n",
    "    ret, data = quote_ctx.get_cur_kline('HK.00700', 2, SubType.K_DAY, AuType.QFQ)  # 获取港股00700最近2个K线数据\n",
    "    if ret == RET_OK:\n",
    "        print(data)\n",
    "        print(data['turnover_rate'][0])   # 取第一条的换手率\n",
    "        print(data['turnover_rate'].values.tolist())   # 转为list\n",
    "    else:\n",
    "        print('error:', data)\n",
    "else:\n",
    "    print('subscription failed', err_message)\n",
    "quote_ctx.close()  # 关闭当条连接，FutuOpenD会在1分钟后自动取消相应股票相应类型的订阅"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "tracked-standard",
   "metadata": {},
   "outputs": [],
   "source": [
    "class CurKlineTest(CurKlineHandlerBase):\n",
    "    def on_recv_rsp(self, rsp_pb):\n",
    "        ret_code, data = super(CurKlineTest,self).on_recv_rsp(rsp_pb)\n",
    "        if ret_code != RET_OK:\n",
    "            print(\"CurKlineTest: error, msg: %s\" % data)\n",
    "            return RET_ERROR, data\n",
    "        print(\"CurKlineTest \", data) # CurKlineTest自己的处理逻辑\n",
    "        return RET_OK, data\n",
    "quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)\n",
    "handler = CurKlineTest()\n",
    "quote_ctx.set_handler(handler)  # 设置实时摆盘回调\n",
    "quote_ctx.subscribe(['HK.00700'], [SubType.K_1M])   # 订阅K线数据类型，FutuOpenD开始持续收到服务器的推送\n",
    "time.sleep(15)  # 设置脚本接收FutuOpenD的推送持续时间为15秒\n",
    "quote_ctx.close()   # 关闭当条连接，FutuOpe"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "strategic-eligibility",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2021-02-27 23:18:44,677 [open_context_base.py] _socket_reconnect_and_wait_ready:255: Start connecting: host=127.0.0.1; port=11111;\n",
      "2021-02-27 23:18:44,680 [open_context_base.py] on_connected:344: Connected : conn_id=9; \n",
      "2021-02-27 23:18:44,684 [open_context_base.py] _handle_init_connect:445: InitConnect ok: conn_id=9; info={'server_version': 500, 'login_user_id': 716900, 'conn_id': 6771448478414688867, 'conn_key': '73C70D17D59280BC', 'conn_iv': '61E32F20120006B6', 'keep_alive_interval': 10, 'is_encrypt': False};\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "         code                 time  is_blank  opened_mins  cur_price  \\\n",
      "0    HK.00700  2021-02-26 09:30:00     False          570      669.0   \n",
      "1    HK.00700  2021-02-26 09:31:00     False          571      673.0   \n",
      "2    HK.00700  2021-02-26 09:32:00     False          572      669.0   \n",
      "3    HK.00700  2021-02-26 09:33:00     False          573      666.5   \n",
      "4    HK.00700  2021-02-26 09:34:00     False          574      666.5   \n",
      "..        ...                  ...       ...          ...        ...   \n",
      "326  HK.00700  2021-02-26 15:56:00     False          956      668.0   \n",
      "327  HK.00700  2021-02-26 15:57:00     False          957      668.5   \n",
      "328  HK.00700  2021-02-26 15:58:00     False          958      668.5   \n",
      "329  HK.00700  2021-02-26 15:59:00     False          959      668.5   \n",
      "330  HK.00700  2021-02-26 16:00:00     False          960      662.5   \n",
      "\n",
      "     last_close   avg_price   volume      turnover  \n",
      "0         691.5  669.000000  1318200  8.818758e+08  \n",
      "1         691.5  669.025472   913700  6.113222e+08  \n",
      "2         691.5  669.051850   400700  2.681480e+08  \n",
      "3         691.5  668.906701   208800  1.392856e+08  \n",
      "4         691.5  668.620700   321400  2.140820e+08  \n",
      "..          ...         ...      ...           ...  \n",
      "326       691.5  671.721987    73400  4.902135e+07  \n",
      "327       691.5  671.705155   116300  7.770395e+07  \n",
      "328       691.5  671.689744   120700  8.069090e+07  \n",
      "329       691.5  671.671691   137100  9.163645e+07  \n",
      "330       691.5  669.527830  7862200  5.210259e+09  \n",
      "\n",
      "[331 rows x 9 columns]\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2021-02-27 23:18:44,768 [network_manager.py] work:366: Close: conn_id=9\n"
     ]
    }
   ],
   "source": [
    "quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)\n",
    "ret_sub, err_message = quote_ctx.subscribe(['HK.00700'], [SubType.RT_DATA], subscribe_push=False)\n",
    "# 先订阅分时数据类型。订阅成功后FutuOpenD将持续收到服务器的推送，False代表暂时不需要推送给脚本\n",
    "if ret_sub == RET_OK:   # 订阅成功\n",
    "    ret, data = quote_ctx.get_rt_data('HK.00700')   # 获取一次分时数据\n",
    "    if ret == RET_OK:\n",
    "        print(data)\n",
    "    else:\n",
    "        print('error:', data)\n",
    "else:\n",
    "    print('subscription failed', err_message)\n",
    "quote_ctx.close()   # 关闭当条连接，FutuOpenD会在1分钟后自动取消相应股票相应类型的订阅"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "complete-butler",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2021-02-27 23:19:08,979 [open_context_base.py] _socket_reconnect_and_wait_ready:255: Start connecting: host=127.0.0.1; port=11111;\n",
      "2021-02-27 23:19:08,982 [open_context_base.py] on_connected:344: Connected : conn_id=10; \n",
      "2021-02-27 23:19:08,985 [open_context_base.py] _handle_init_connect:445: InitConnect ok: conn_id=10; info={'server_version': 500, 'login_user_id': 716900, 'conn_id': 6771448580344588555, 'conn_key': '56DC3217D592BC4F', 'conn_iv': '7F7B6FFA1700A6C7', 'keep_alive_interval': 10, 'is_encrypt': False};\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "RTDataTest         code                 time  is_blank  opened_mins  cur_price  \\\n",
      "0  HK.00700  2021-02-26 16:00:00     False          960      662.5   \n",
      "\n",
      "   last_close  avg_price      turnover   volume  \n",
      "0       691.5  669.52783  5.210259e+09  7862200  \n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2021-02-27 23:19:24,016 [network_manager.py] work:366: Close: conn_id=10\n"
     ]
    }
   ],
   "source": [
    "\n",
    "class RTDataTest(RTDataHandlerBase):\n",
    "    def on_recv_rsp(self, rsp_pb):\n",
    "        ret_code, data = super(RTDataTest, self).on_recv_rsp(rsp_pb)\n",
    "        if ret_code != RET_OK:\n",
    "            print(\"RTDataTest: error, msg: %s\" % data)\n",
    "            return RET_ERROR, data\n",
    "        print(\"RTDataTest \", data) # RTDataTest自己的处理逻辑\n",
    "        return RET_OK, data\n",
    "quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)\n",
    "handler = RTDataTest()\n",
    "quote_ctx.set_handler(handler)  # 设置实时分时推送回调\n",
    "quote_ctx.subscribe(['HK.00700'], [SubType.RT_DATA]) # 订阅分时类型，FutuOpenD开始持续收到服务器的推送\n",
    "time.sleep(15)  # 设置脚本接收FutuOpenD的推送持续时间为15秒\n",
    "quote_ctx.close()   # 关闭当条连接，FutuOpenD会在1分钟后自动取消相应股票相应类型的订阅    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "id": "respected-gravity",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2021-02-27 23:20:43,604 [open_context_base.py] _socket_reconnect_and_wait_ready:255: Start connecting: host=127.0.0.1; port=11111;\n",
      "2021-02-27 23:20:43,607 [open_context_base.py] on_connected:344: Connected : conn_id=15; \n",
      "2021-02-27 23:20:43,610 [open_context_base.py] _handle_init_connect:445: InitConnect ok: conn_id=15; info={'server_version': 500, 'login_user_id': 716900, 'conn_id': 6771448977233603588, 'conn_key': '2B3FC317D5924C44', 'conn_iv': '7D13E6922800F678', 'keep_alive_interval': 10, 'is_encrypt': False};\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Empty DataFrame\n",
      "Columns: [code, name, lot_size, stock_type, option_type, stock_owner, strike_time, strike_price, suspension, stock_id, index_option_type]\n",
      "Index: []\n"
     ]
    },
    {
     "ename": "KeyError",
     "evalue": "0",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mValueError\u001b[0m                                Traceback (most recent call last)",
      "\u001b[0;32m~/.pyenv/versions/3.7.0/lib/python3.7/site-packages/pandas/core/indexes/range.py\u001b[0m in \u001b[0;36mget_loc\u001b[0;34m(self, key, method, tolerance)\u001b[0m\n\u001b[1;32m    354\u001b[0m                 \u001b[0;32mtry\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 355\u001b[0;31m                     \u001b[0;32mreturn\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_range\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mindex\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mnew_key\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m    356\u001b[0m                 \u001b[0;32mexcept\u001b[0m \u001b[0mValueError\u001b[0m \u001b[0;32mas\u001b[0m \u001b[0merr\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;31mValueError\u001b[0m: 0 is not in range",
      "\nThe above exception was the direct cause of the following exception:\n",
      "\u001b[0;31mKeyError\u001b[0m                                  Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-31-34d62ed71e5a>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[1;32m      7\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mret\u001b[0m \u001b[0;34m==\u001b[0m \u001b[0mRET_OK\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m      8\u001b[0m     \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mdata\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 9\u001b[0;31m     \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mdata\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m'code'\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m)\u001b[0m    \u001b[0;31m# 取第一条的股票代码\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m     10\u001b[0m     \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mdata\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m'code'\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mvalues\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mtolist\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m   \u001b[0;31m# 转为list\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m     11\u001b[0m \u001b[0;32melse\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;32m~/.pyenv/versions/3.7.0/lib/python3.7/site-packages/pandas/core/series.py\u001b[0m in \u001b[0;36m__getitem__\u001b[0;34m(self, key)\u001b[0m\n\u001b[1;32m    880\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    881\u001b[0m         \u001b[0;32melif\u001b[0m \u001b[0mkey_is_scalar\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 882\u001b[0;31m             \u001b[0;32mreturn\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_get_value\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mkey\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m    883\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    884\u001b[0m         \u001b[0;32mif\u001b[0m \u001b[0mis_hashable\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mkey\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;32m~/.pyenv/versions/3.7.0/lib/python3.7/site-packages/pandas/core/series.py\u001b[0m in \u001b[0;36m_get_value\u001b[0;34m(self, label, takeable)\u001b[0m\n\u001b[1;32m    988\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    989\u001b[0m         \u001b[0;31m# Similar to Index.get_value, but we do not fall back to positional\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 990\u001b[0;31m         \u001b[0mloc\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mindex\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mget_loc\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mlabel\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m    991\u001b[0m         \u001b[0;32mreturn\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mindex\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_get_values_for_loc\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mloc\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mlabel\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    992\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;32m~/.pyenv/versions/3.7.0/lib/python3.7/site-packages/pandas/core/indexes/range.py\u001b[0m in \u001b[0;36mget_loc\u001b[0;34m(self, key, method, tolerance)\u001b[0m\n\u001b[1;32m    355\u001b[0m                     \u001b[0;32mreturn\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_range\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mindex\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mnew_key\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    356\u001b[0m                 \u001b[0;32mexcept\u001b[0m \u001b[0mValueError\u001b[0m \u001b[0;32mas\u001b[0m \u001b[0merr\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 357\u001b[0;31m                     \u001b[0;32mraise\u001b[0m \u001b[0mKeyError\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mkey\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;32mfrom\u001b[0m \u001b[0merr\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m    358\u001b[0m             \u001b[0;32mraise\u001b[0m \u001b[0mKeyError\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mkey\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    359\u001b[0m         \u001b[0;32mreturn\u001b[0m \u001b[0msuper\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mget_loc\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mkey\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mmethod\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mmethod\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mtolerance\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mtolerance\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;31mKeyError\u001b[0m: 0"
     ]
    }
   ],
   "source": [
    "quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)\n",
    "\n",
    "data_filter = OptionDataFilter()\n",
    "data_filter.delta_min = 0.4\n",
    "data_filter.delta_max = 0.6\n",
    "ret, data = quote_ctx.get_option_chain('HK.00700', IndexOptionType.NORMAL, '2021-02-27', '2021-03-10', OptionType.ALL, OptionCondType.ALL, data_filter)\n",
    "if ret == RET_OK:\n",
    "    print(data)\n",
    "    print(data['code'][0])    # 取第一条的股票代码\n",
    "    print(data['code'].values.tolist())   # 转为list\n",
    "else:\n",
    "    print('error:', data)\n",
    "quote_ctx.close() # 结束后记得关闭当条连接，防止连接条数用尽"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "id": "adjustable-punch",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2021-02-27 23:21:18,131 [open_context_base.py] _socket_reconnect_and_wait_ready:255: Start connecting: host=127.0.0.1; port=11111;\n",
      "2021-02-27 23:21:18,134 [open_context_base.py] on_connected:344: Connected : conn_id=16; \n",
      "2021-02-27 23:21:18,137 [open_context_base.py] _handle_init_connect:445: InitConnect ok: conn_id=16; info={'server_version': 500, 'login_user_id': 716900, 'conn_id': 6771449122049086274, 'conn_key': '57EEF717D5922816', 'conn_iv': 'EA31051133003601', 'keep_alive_interval': 10, 'is_encrypt': False};\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "99 99        stock        name stock_owner  type issuer maturity_time   list_time  \\\n",
      "0   HK.22954  腾讯法巴一三购C.C    HK.00700  CALL     BP    2021-03-02  2020-08-11   \n",
      "1   HK.12241  腾讯国君一三购B.C    HK.00700  CALL     GJ    2021-03-02  2020-10-21   \n",
      "2   HK.14111  腾讯中银一二购A.C    HK.00700  CALL     BI    2021-02-26  2020-10-28   \n",
      "3   HK.15861  腾讯花旗一二购C.C    HK.00700  CALL     CT    2021-02-25  2020-11-05   \n",
      "4   HK.21758  腾讯国君一七购B.C    HK.00700  CALL     GJ    2021-07-05  2021-01-22   \n",
      "..       ...         ...         ...   ...    ...           ...         ...   \n",
      "94  HK.21793  腾讯汇丰一乙购B.C    HK.00700  CALL     HS    2021-12-31  2021-01-22   \n",
      "95  HK.20004  腾讯花旗一四购G.C    HK.00700  CALL     CT    2021-04-29  2021-01-19   \n",
      "96  HK.18867  腾讯瑞信一八购C.C    HK.00700  CALL     CS    2021-08-24  2021-02-26   \n",
      "97  HK.19059  腾讯国君一九购B.C    HK.00700  CALL     GJ    2021-09-07  2021-02-26   \n",
      "98  HK.19271  腾讯摩通一四购B.C    HK.00700  CALL     JP    2021-04-23  2020-07-28   \n",
      "\n",
      "   last_trade_time  recovery_price  conversion_ratio  ...  low_price  \\\n",
      "0       2021-02-24             NaN             100.0  ...      0.000   \n",
      "1       2021-02-24             NaN             100.0  ...      0.000   \n",
      "2       2021-02-22             NaN             100.0  ...      0.000   \n",
      "3       2021-02-19             NaN             100.0  ...      0.000   \n",
      "4       2021-06-28             NaN             100.0  ...      0.000   \n",
      "..             ...             ...               ...  ...        ...   \n",
      "94      2021-12-24             NaN             500.0  ...      0.181   \n",
      "95      2021-04-23             NaN             100.0  ...      0.136   \n",
      "96      2021-08-18             NaN             500.0  ...      0.101   \n",
      "97      2021-09-01             NaN             500.0  ...      0.100   \n",
      "98      2021-04-19             NaN             100.0  ...      0.104   \n",
      "\n",
      "    implied_volatility  delta  effective_leverage  list_timestamp  \\\n",
      "0               65.671  0.381              19.416    1.597075e+09   \n",
      "1               63.889  0.374              20.144    1.603210e+09   \n",
      "2              236.607  0.348              12.808    1.603814e+09   \n",
      "3                0.000  0.000               0.000    1.604506e+09   \n",
      "4               45.739  0.218               7.257    1.611245e+09   \n",
      "..                 ...    ...                 ...             ...   \n",
      "94              40.229  0.547               4.004    1.611245e+09   \n",
      "95              44.443  0.219              10.289    1.610986e+09   \n",
      "96              45.633  0.400               5.196    1.614269e+09   \n",
      "97              47.228  0.383               4.975    1.614269e+09   \n",
      "98              46.790  0.175              10.835    1.595866e+09   \n",
      "\n",
      "    last_trade_timestamp maturity_timestamp  upper_strike_price  \\\n",
      "0           1.614096e+09       1.614614e+09                 NaN   \n",
      "1           1.614096e+09       1.614614e+09                 NaN   \n",
      "2           1.613923e+09       1.614269e+09                 NaN   \n",
      "3           1.613664e+09       1.614182e+09                 NaN   \n",
      "4           1.624810e+09       1.625414e+09                 NaN   \n",
      "..                   ...                ...                 ...   \n",
      "94          1.640275e+09       1.640880e+09                 NaN   \n",
      "95          1.619107e+09       1.619626e+09                 NaN   \n",
      "96          1.629216e+09       1.629734e+09                 NaN   \n",
      "97          1.630426e+09       1.630944e+09                 NaN   \n",
      "98          1.618762e+09       1.619107e+09                 NaN   \n",
      "\n",
      "    lower_strike_price  inline_price_status  \n",
      "0                  NaN                  NaN  \n",
      "1                  NaN                  NaN  \n",
      "2                  NaN                  NaN  \n",
      "3                  NaN                  NaN  \n",
      "4                  NaN                  NaN  \n",
      "..                 ...                  ...  \n",
      "94                 NaN                  NaN  \n",
      "95                 NaN                  NaN  \n",
      "96                 NaN                  NaN  \n",
      "97                 NaN                  NaN  \n",
      "98                 NaN                  NaN  \n",
      "\n",
      "[99 rows x 45 columns]\n",
      "HK.22954\n",
      "['HK.22954', 'HK.12241', 'HK.14111', 'HK.15861', 'HK.21758', 'HK.25237', 'HK.25944', 'HK.27000', 'HK.28478', 'HK.29127', 'HK.24841', 'HK.26090', 'HK.25023', 'HK.29932', 'HK.21110', 'HK.29937', 'HK.11534', 'HK.15294', 'HK.19581', 'HK.16401', 'HK.17019', 'HK.16952', 'HK.29138', 'HK.16830', 'HK.24642', 'HK.29928', 'HK.29718', 'HK.27074', 'HK.16920', 'HK.25813', 'HK.29709', 'HK.15011', 'HK.29145', 'HK.11841', 'HK.22381', 'HK.11052', 'HK.22500', 'HK.23589', 'HK.24299', 'HK.25434', 'HK.23180', 'HK.19347', 'HK.20742', 'HK.16814', 'HK.26133', 'HK.17160', 'HK.15476', 'HK.23047', 'HK.11156', 'HK.17627', 'HK.21436', 'HK.13788', 'HK.12988', 'HK.18977', 'HK.19992', 'HK.21571', 'HK.20995', 'HK.20776', 'HK.11057', 'HK.17882', 'HK.22412', 'HK.23166', 'HK.24187', 'HK.21121', 'HK.19412', 'HK.23584', 'HK.12131', 'HK.20600', 'HK.23333', 'HK.19837', 'HK.11777', 'HK.21217', 'HK.21054', 'HK.24426', 'HK.11205', 'HK.14207', 'HK.13745', 'HK.23686', 'HK.18355', 'HK.22330', 'HK.17263', 'HK.11357', 'HK.15125', 'HK.22567', 'HK.27917', 'HK.18266', 'HK.12488', 'HK.22722', 'HK.21519', 'HK.23136', 'HK.24389', 'HK.20664', 'HK.15471', 'HK.20662', 'HK.21793', 'HK.20004', 'HK.18867', 'HK.19059', 'HK.19271']\n",
      "200 4818         stock        name stock_owner  type issuer maturity_time   list_time  \\\n",
      "0    HK.20614  平安瑞信一二购A.C    HK.02318  CALL     CS    2021-02-26  2018-01-03   \n",
      "1    HK.24932  澳博瑞银一三购A.C    HK.00880  CALL     UB    2021-03-22  2019-01-31   \n",
      "2    HK.17892  平安瑞信一二购B.C    HK.02318  CALL     CS    2021-02-26  2019-04-26   \n",
      "3    HK.28440  平安中银一二购A.C    HK.02318  CALL     BI    2021-02-19  2019-09-13   \n",
      "4    HK.11558  中科瑞信一二购A.C    HK.02357  CALL     CS    2021-02-26  2019-10-08   \n",
      "..        ...         ...         ...   ...    ...           ...         ...   \n",
      "195  HK.11637  港交瑞银一三购A.C    HK.00388  CALL     UB    2021-03-24  2020-05-27   \n",
      "196  HK.11820  美团中银一四沽A.P    HK.03690   PUT     BI    2021-04-30  2020-05-28   \n",
      "197  HK.11901  联想瑞信一乙购A.C    HK.00992  CALL     CS    2021-12-23  2020-05-28   \n",
      "198  HK.50326  恒指瑞信三一牛X.C   HK.800000  BULL     CS    2023-01-30  2020-05-29   \n",
      "199  HK.50329  恒指瑞信三二牛T.C   HK.800000  BULL     CS    2023-02-27  2020-05-29   \n",
      "\n",
      "    last_trade_time  recovery_price  conversion_ratio  ...  low_price  \\\n",
      "0        2021-02-22             NaN             100.0  ...        0.0   \n",
      "1        2021-03-16             NaN              10.0  ...        0.0   \n",
      "2        2021-02-22             NaN              50.0  ...        0.0   \n",
      "3        2021-02-11             NaN              50.0  ...        0.0   \n",
      "4        2021-02-22             NaN               5.0  ...        0.0   \n",
      "..              ...             ...               ...  ...        ...   \n",
      "195      2021-03-18             NaN             100.0  ...        0.0   \n",
      "196      2021-04-26             NaN             100.0  ...        0.0   \n",
      "197      2021-12-17             NaN               5.0  ...        0.0   \n",
      "198      2023-01-27         22728.0           12000.0  ...        0.0   \n",
      "199      2023-02-24         22428.0           12000.0  ...        0.0   \n",
      "\n",
      "     implied_volatility  delta  effective_leverage  list_timestamp  \\\n",
      "0                 0.000  0.000               0.000    1.514909e+09   \n",
      "1                66.479  0.871               4.873    1.548864e+09   \n",
      "2               198.510  0.109              20.775    1.556208e+09   \n",
      "3                 0.000  0.000               0.000    1.568304e+09   \n",
      "4                 0.000  0.000               0.000    1.570464e+09   \n",
      "..                  ...    ...                 ...             ...   \n",
      "195             107.463  0.954               2.579    1.590509e+09   \n",
      "196             147.268 -0.020              -3.400    1.590595e+09   \n",
      "197              46.582  0.982               1.767    1.590595e+09   \n",
      "198                 NaN    NaN               5.250    1.590682e+09   \n",
      "199                 NaN    NaN               4.979    1.590682e+09   \n",
      "\n",
      "     last_trade_timestamp maturity_timestamp  upper_strike_price  \\\n",
      "0            1.613923e+09       1.614269e+09                 NaN   \n",
      "1            1.615824e+09       1.616342e+09                 NaN   \n",
      "2            1.613923e+09       1.614269e+09                 NaN   \n",
      "3            1.612973e+09       1.613664e+09                 NaN   \n",
      "4            1.613923e+09       1.614269e+09                 NaN   \n",
      "..                    ...                ...                 ...   \n",
      "195          1.615997e+09       1.616515e+09                 NaN   \n",
      "196          1.619366e+09       1.619712e+09                 NaN   \n",
      "197          1.639670e+09       1.640189e+09                 NaN   \n",
      "198          1.674749e+09       1.675008e+09                 NaN   \n",
      "199          1.677168e+09       1.677427e+09                 NaN   \n",
      "\n",
      "     lower_strike_price  inline_price_status  \n",
      "0                   NaN                  NaN  \n",
      "1                   NaN                  NaN  \n",
      "2                   NaN                  NaN  \n",
      "3                   NaN                  NaN  \n",
      "4                   NaN                  NaN  \n",
      "..                  ...                  ...  \n",
      "195                 NaN                  NaN  \n",
      "196                 NaN                  NaN  \n",
      "197                 NaN                  NaN  \n",
      "198                 NaN                  NaN  \n",
      "199                 NaN                  NaN  \n",
      "\n",
      "[200 rows x 45 columns]\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2021-02-27 23:21:18,419 [network_manager.py] work:366: Close: conn_id=16\n"
     ]
    }
   ],
   "source": [
    "quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)\n",
    "\n",
    "req = WarrantRequest()\n",
    "req.sort_field = SortField.TURNOVER\n",
    "req.type_list = WrtType.CALL\n",
    "req.cur_price_min = 0.1\n",
    "req.cur_price_max = 0.2\n",
    "ret, ls = quote_ctx.get_warrant(\"HK.00700\", req)\n",
    "if ret == RET_OK:  # 先判断接口返回是否正常，再取数据\n",
    "    warrant_data_list, last_page, all_count = ls\n",
    "    print(len(warrant_data_list), all_count, warrant_data_list)\n",
    "    print(warrant_data_list['stock'][0])    # 取第一条的窝轮代码\n",
    "    print(warrant_data_list['stock'].values.tolist())   # 转为list\n",
    "else:\n",
    "    print('error: ', ls)\n",
    "    \n",
    "req = WarrantRequest()\n",
    "req.sort_field = SortField.TURNOVER\n",
    "req.issuer_list = ['UB','CS','BI']\n",
    "ret, ls = quote_ctx.get_warrant(Market.HK, req)\n",
    "if ret == RET_OK: \n",
    "    warrant_data_list, last_page, all_count = ls\n",
    "    print(len(warrant_data_list), all_count, warrant_data_list)\n",
    "else:\n",
    "    print('error: ', ls)\n",
    "\n",
    "quote_ctx.close()  # 所有接口结尾加上这条close，防止连接条数用尽"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fundamental-region",
   "metadata": {},
   "outputs": [],
   "source": [
    "quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)\n",
    "\n",
    "ret, data = quote_ctx.get_user_security(\"A\")\n",
    "if ret == RET_OK:\n",
    "    print(data)\n",
    "    print(data['code'][0])    # 取第一条的股票代码\n",
    "    print(data['code'].values.tolist())   # 转为list\n",
    "else:\n",
    "    print('error:', data)\n",
    "quote_ctx.close() # 结束后记得关闭当条连接，防止连接条数用尽"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
